package cn.lic.tool.poi.excel;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.TypeUtils;

public class Utils {
	
	public static String join(Object[] arr) {
		return join(arr, null);
	}
	
	public static String join(Object[] arr, String split) {
		if (arr == null) {
			return null;
		}
		if (arr.length == 0) {
			return "";
		}
		if (split == null) {
			split = ", ";
		}
		StringBuffer sb = new StringBuffer();
		for (Object a : arr) {
			sb.append(split);
			sb.append(TypeUtils.castToString(a));
		}
		return sb.substring(split.length());
	}
		
	/**
	 * 替换字符串中的变量， 如果字符串中没有要替换的变量则返回null,否则返回替换后的字符串
	 * @param str
	 * @param params
	 * @return
	 */
		public static String replace(String str, JSONObject params) {
			StringBuffer sb = new StringBuffer();
			Pattern pattern = Pattern.compile("\\$\\{[\\w+\\.]+\\}");
			Matcher m = pattern.matcher(str);
			while(m.find()) {
				String group = m.group();
				String key = group.substring(2, group.length() - 1);
				String val = params.getOrDefault(key, group).toString();
				m.appendReplacement(sb, val);
			}
			if (sb.length() == 0) {
				return null;
			}
			m.appendTail(sb);
			
			return sb.toString();
		}
}
